using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using ExcellOnServices.Models.Mapping;
using System.Linq;
using ExcellOnServices.Models.Utils;

namespace ExcellOnServices.Models
{
	public partial class ExcellOnServicesContext : DbContext
	{
		static ExcellOnServicesContext() {
			Database.SetInitializer<ExcellOnServicesContext>(null);
		}

		public ExcellOnServicesContext()
			: base("Name=ExcellOnServicesContext") {
		}

		public DbSet<Account> Accounts { get; set; }
		public DbSet<Accounts_Admin> Accounts_Admin { get; set; }
		public DbSet<Accounts_Company> Accounts_Company { get; set; }
		public DbSet<Category> Categories { get; set; }
		public DbSet<OrderItem> OrderItems { get; set; }
		public DbSet<Order> Orders { get; set; }
		public DbSet<Product> Products { get; set; }
		public DbSet<Role> Roles { get; set; }
		public DbSet<Service> Services { get; set; }

		protected override void OnModelCreating(DbModelBuilder modelBuilder) {
			modelBuilder.Configurations.Add(new AccountMap());
			modelBuilder.Configurations.Add(new Accounts_AdminMap());
			modelBuilder.Configurations.Add(new Accounts_CompanyMap());
			modelBuilder.Configurations.Add(new CategoryMap());
			modelBuilder.Configurations.Add(new OrderItemMap());
			modelBuilder.Configurations.Add(new OrderMap());
			modelBuilder.Configurations.Add(new ProductMap());
			modelBuilder.Configurations.Add(new RoleMap());
			modelBuilder.Configurations.Add(new ServiceMap());
		}

		public override int SaveChanges() {
			// fix trackable entities
			var trackables = ChangeTracker.Entries();

			if (trackables != null) {
				// added
				foreach (var item in trackables.Where(t => t.State == EntityState.Added)) {
					var entity = item.Entity;

					if (ContextHelper.IsPropertyExists(entity, "CreatedDateTime")) {
						ContextHelper.SetValue(entity, "CreatedDateTime", System.DateTime.Now);
					}

					if (ContextHelper.IsPropertyExists(entity, "ModifiedDateTime")) {
						ContextHelper.SetValue(entity, "ModifiedDateTime", System.DateTime.Now);
					}
				}
				// modified
				foreach (var item in trackables.Where(t => t.State == EntityState.Modified)) {
					var entity = item.Entity;

					if (ContextHelper.IsPropertyExists(entity, "ModifiedDateTime")) {
						ContextHelper.SetValue(entity, "ModifiedDateTime", System.DateTime.Now);
					}
				}
			}

			return base.SaveChanges();
		}

	}
}
